package com.mc.wsdemo.java;

import com.alibaba.fastjson.JSON;
import com.mc.wsdemo.Entity.Message;
import com.mc.wsdemo.spring.SessionBean;
import com.mc.wsdemo.spring.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.socket.WebSocketSession;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 监听websocket地址/myWs
 *
 * @author 未来
 */
@ServerEndpoint("/myWs/{username}")
@Component
@Slf4j
public class WsServerEndpont {
    //    static Map<String,Session> sessionMap = new ConcurrentHashMap<>();
    private static Map<String, User> sessionBeanMap;

    private static ConcurrentHashMap<String, Message> sessionMessageMap;

    private static ConcurrentHashMap<String, Session> sessionMap;
    private static AtomicInteger clientIdMaker;


    static {
        sessionBeanMap = new ConcurrentHashMap<>();
        clientIdMaker = new AtomicInteger(1);
        sessionMap = new ConcurrentHashMap<>();
        sessionMessageMap = new ConcurrentHashMap<>();
    }

    //连接建立时执行的操作
    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        log.info("Session:" + session.getId());
        Message message = new Message(username, "-2", "进入群聊", session, new Date());
        sessionMessageMap.put(session.getId(), message);
//        //存储相关的属性值，存取相关的session
//        sessionMap.put(username, session);
        log.info("websocket is open:" + session.getId());
        broadcast(message);
//        for (String key : sessionBeanMap.keySet()) {
//            try {
//                sessionBeanMap.get(key).getSession().getBasicRemote().sendText("<p style='text-align:center; color:blue;'>" + "进入群聊：" + session.getId() + "</p>");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }

    }

    //收到了客户端消息执行的操作
    @OnMessage
    public void onMessage(String message, Session session) {
        Message msg = JSON.parseObject(message, Message.class);
        msg.setDate(new Date());
        System.out.println("Text" + msg.getText());
        System.out.println("To" + msg.getUserTo());
        //指定-1是广播消息
        if (msg.getUserTo().equals("-1")) {
            //广播消息:JSON.toJSONString(msg,true)
            broadcast(msg);
        } else {
            //指定人发送消息
            sendOneInfo(msg);
        }
//        try {
//            User user = JSON.parseObject(text, com.mc.wsdemo.spring.User.class);
//            System.out.println(user.getUserId());
//            Set<String> strings = sessionBeanMap.keySet();
//            if (!strings.contains(String.valueOf(user.getUserId()))) {
//                //不存在map当中
//                sessionBeanMap.put(session.getId(), new User(Integer.parseInt(session.getId()), user.getAction(), session));
//            }
//        } catch (Exception e) {
//            log.info("收到了一条消息：" + text);
//            for (String key : sessionBeanMap.keySet()) {
//                try {
//                    if (key.equals(session.getId())) {
//                        sessionBeanMap.get(key).getSession().getBasicRemote().sendText("<p style='text-align:right; color:black;'>" + "已收到" + session.getId() + "的消息:" + text + "</p>");
//                    } else {
//                        sessionBeanMap.get(key).getSession().getBasicRemote().sendText("<p style='text-align:left; color:black;'>" + "已收到" + session.getId() + "的消息:" + text + "</p>");
//                    }
////                    sessionBeanMap.get(key).getSession().getBasicRemote().sendText("<p style='text-align:center; color:red;'>"+"已收到"+session.getId()+"的消息:" +text+"</p>");
//                } catch (IOException ex) {
//                    throw new RuntimeException(ex);
//                }
//            }
//        }
    }

    //连接关闭的时候执行的操作
    @OnClose
    public void onClose(Session session) {
        log.info("websocket is close" + session.getId());
        String userName = sessionMessageMap.get(session.getId()).getUserName();
//        sessionBeanMap.remove(session.getId());
        sessionMessageMap.remove(session.getId());
        for (String key : sessionMessageMap.keySet()) {
            try {
                sessionMessageMap.get(key).getSession().getBasicRemote().sendText("<p style='text-align:center; color:red;'>" + "连接关闭:" + userName + "</p>");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        for (String key : sessionBeanMap.keySet()) {
//            try {
//                sessionBeanMap.get(key).getSession().getBasicRemote().sendText("<p style='text-align:center; color:red;'>" + "连接关闭" + id + "</p>");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
    }

    /**
     * 给指定用户发送信息
     */
    public void sendOneInfo(Message msg) {
        for (String key : sessionMessageMap.keySet()) {
            //判断是否是两个人的信息
            if (sessionMessageMap.get(key).getUserName().equals(msg.getUserTo())) {
                try {
                    sessionMessageMap.get(key).getSession().getBasicRemote().sendText("<p style='text-align:left; color:blue;'>" + "已收到" + msg.getUserName() + "的消息:" + msg.getText() + "</p>");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else if (msg.getUserName().equals(sessionMessageMap.get(key).getUserName())) {
                try {
                    sessionMessageMap.get(key).getSession().getBasicRemote().sendText("<p style='text-align:right; color:black;'>" + "已发送给" + msg.getUserTo() + "的消息:" + msg.getText() + "</p>");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

//        Session session = sessionMap.get(userName);
//        if (session != null) {
//            synchronized (session) {
//                System.out.println("发送数据：" + msg.getText());
//                try {
//                    session.getBasicRemote().sendText(msg.getText());
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//        }

        }
    }

    public void broadcast(Message msg) {
        //获取map的所有值
        System.out.println("sessionMessageMap.values:" + sessionMessageMap.values());
        for (Message message : sessionMessageMap.values()) {
            try {
                synchronized (message.getSession()) {
                    System.out.println("发送数据：" + msg.getText());
                    if (msg.getUserTo().equals("-2")) {
                        message.getSession().getBasicRemote().sendText("<p style='text-align:center; color:red;'>" + msg.getUserName() + "进入群聊！！" + "</p>");
                    } else if (msg.getUserName().equals(message.getUserName())) {
                        message.getSession().getBasicRemote().sendText("<p style='text-align:right; color:black;'>" + "已收到" + msg.getUserName() + "的消息:" + msg.getText() + "</p>");
                    } else {
                        message.getSession().getBasicRemote().sendText("<p style='text-align:left; color:blue;'>" + "已收到" + msg.getUserName() + "的消息:" + msg.getText() + "</p>");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //每2s发送给客户端心跳消息:大屏显示和数据实时展示使用
//    @Scheduled(fixedRate = 4000)//四秒返回数据给前端
//    public void sendMsg() throws IOException {
//        for (String key : sessionBeanMap.keySet()) {
//            sessionBeanMap.get(key).getSession().getBasicRemote().sendText("{  \n" +
//                    "  \"name\": \"John Doe\",  \n" +
//                    "  \"age\": 30,  \n" +
//                    "  \"email\": \"johndoe@example.com\",  \n" +
//                    "  \"isStudent\": false,  \n" +
//                    "  \"hobbies\": [\"reading\", \"traveling\", \"photography\"],  \n" +
//                    "  \"address\": {  \n" +
//                    "    \"street\": \"123 Main St\",  \n" +
//                    "    \"city\": \"New York\",  \n" +
//                    "    \"state\": \"NY\",  \n" +
//                    "    \"zip\": \"10001\"  \n" +
//                    "  }  \n" +
//                    "}");
//        }
//    }
}
